package com.mstore.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.csvreader.CsvReader;
import com.mstore.pojo.Account;
import com.mstore.pojo.BaseMember;
import com.mstore.pojo.EnterpriseIntegralRule;
import com.mstore.pojo.Member;
import com.mstore.service.BaseMemberService;
import com.mstore.service.EnterpriseIntegralRuleService;
import com.mstore.service.MemberService;
import com.opensymphony.xwork2.ActionContext;

/**
 * 导入会员信息
 */
public class DateBaseImportAction extends BaseAction {

	private static final long serialVersionUID = -3721722617567651556L;

	private File[] upload;

	private String[] uploadContentType;

	private String[] uploadFileName;

	private String result;

	private MemberService memberService;

	private Map<String, Object> session = ActionContext.getContext()
			.getSession();

	private String basePath = "/usr/local/csvUpload";

	// 重复手机号集合
	private List<String> repeatMember = new ArrayList<String>();

	private static Logger logger = Logger.getLogger(DateBaseImportAction.class
			.getName());

	private BaseMemberService baseMemberService;

	private EnterpriseIntegralRuleService enterpriseIntegralRuleService;

	/**
	 * 读取上传的csv文件并导入数据库
	 */
	public String readCSVFileAndImport() {
		try {
			File[] files = getUpload();
			// 用时间戳重命名上传文件名
			String fileName = "mb" + System.currentTimeMillis() + ".csv";
			for (int i = 0; i < files.length; i++) {
				File uploadPath = new File(basePath); // 上传文件目录
				if (!uploadPath.exists()) {
					uploadPath.mkdirs();
				}

				FileOutputStream fos = new FileOutputStream(uploadPath + "/"
						+ fileName);
				FileInputStream fis = new FileInputStream(files[i]);
				byte[] buffer = new byte[1024];
				int len = 0;

				while ((len = fis.read(buffer)) > 0) {
					fos.write(buffer, 0, len);
				}
			}

			List<String[]> csvList = new ArrayList<String[]>(); // 用来保存数据
			String csvFilePath = basePath + "/" + fileName;
			CsvReader reader = new CsvReader(csvFilePath, ',',
					Charset.forName("GBK")); // 一般用这编码读就可以了

			reader.readHeaders(); // 跳过表头 如果需要表头的话，不要写这句。

			while (reader.readRecord()) { // 逐行读入除表头的数据
				csvList.add(reader.getValues());
			}
			reader.close();

			Object act = session.get("account");
			if (act == null) {
				result = "系统异常，请重新登陆！";
				return "error";
			}
			Account account = (Account) act;
			Long eaId = account.getId();

			// 手机号验证标示
			boolean error = false;
			// 不向c_member表插入数据标示
			// 初始为false，表示可以向c_member表插入数据
			boolean notAddInCMember = false;

			Member member = new Member(); // 初始化Member类
			BaseMember baseMember = new BaseMember(); // 初始化BaseMember类
			for (int row = 0; row < csvList.size(); row++) {
				String name = null;
				String sex = null;
				double score = 0d;
				double balance = 0d;

				String[] cells = csvList.get(row);
				for (int col = 0; col < cells.length; col++) {
					String value = cells[col].trim();
					switch (col) {
						case 0:
							if ("".equals(value) || value == null) {
								error = true;
								break;
							}
							member.setMobile(value); // 设置手机号
							member.setCreateTime(super.getCreateTime()); // 设置时间
							member.setType(1); // 设置会员类型1;
							member.setEaId(eaId); // 设置企业ID
							Member mem = memberService
									.getmemberByMobile(member);
							if (mem != null) {
								BaseMember bm = baseMemberService
										.getOneBaseMemberByMemberIdAndEaId(
												mem.getId(), eaId);
								if (bm != null) {
									String mobile = mem.getMobile();
									if (repeatMember.indexOf(mobile) == -1)
										repeatMember.add(mobile);
									error = true;
								}
								else {
									// 不向c_member表插入数据
									member.setId(mem.getId());
									notAddInCMember = true;
								}
							}
							break;
						case 1:
							if (value != null && !"".equals(value)) {
								score = Double.parseDouble(value);
							}
							break;
						case 2:
							if (value != null && !"".equals(value)) {
								balance = Double.parseDouble(value);
							}
							break;
						case 3:
							if (value != null && !"".equals(value)) {
								name = value;
							}
							break;
						case 4:
							if (value != null && !"".equals(value)) {
								sex = value;
							}
							break;
					}

					if (error) { // 跳出列循环
						break;
					}
				}

				if (error) {
					error = false;
					continue; // 忽略本次行循环
				}

				member.setName(name);
				member.setSex(sex);
				if (!notAddInCMember) {
					memberService.addMember(member); // 插入一条Member数据
				}
				else {
					notAddInCMember = false;
				}

				baseMember.setScore(score);
				baseMember.setBalance(balance);
				baseMember.setMemberId(member.getId());
				baseMember.setCreateTime(getCreateTime());
				baseMember.setEaId(eaId);
				baseMember.setLevel(getMemberLevelname(eaId, score));

				baseMemberService.save(baseMember);
			}
		}
		catch (FileNotFoundException e) {
			e.printStackTrace();
			logger.error("导入csv异常", e);
			result = "数据未导入数据库！可能您的csv文件编码格式不正确，请尽量使用本系统提供的模板文件编辑。";
			return "importSuccess";
		}
		catch (IOException e) {
			e.printStackTrace();
			logger.error("导入csv异常", e);
			result = "数据未导入数据库！可能您的csv文件编码格式不正确，请尽量使用本系统提供的模板文件编辑。";
			return "importSuccess";
		}
		catch (Exception e) {
			logger.error("导入csv异常", e);
			result = "数据未导入数据库！可能您的csv文件编码格式不正确，请尽量使用本系统提供的模板文件编辑。";
			return "importSuccess";
		}

		result = "数据已成功导入数据库！";
		return "importSuccess";
	}

	private String getMemberLevelname(Long eaId, double score) {
		String level = null;
		EnterpriseIntegralRule integralRule = new EnterpriseIntegralRule();
		integralRule.setEaId(eaId);
		List<EnterpriseIntegralRule> integralRules = enterpriseIntegralRuleService
				.watchEnterpriseIntegralRule(integralRule);
		for (int i = 0; i < integralRules.size(); i++) {
			if ((int) score >= integralRules.get(i).getMinValue()
					&& score < integralRules.get(i).getMaxValue()) {
				level = integralRules.get(i).getName();
				break;                                            
			}
			if (i == integralRules.size() - 1) {
				if (score >= integralRules.get(i).getMaxValue()) {
					level = integralRules.get(i).getName();
				}
			}
		}
		return level;
	}

	public void setUpload(File[] upload) {
		this.upload = upload;
	}

	public void setUploadContentType(String[] uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public void setUploadFileName(String[] uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public File[] getUpload() {
		return (this.upload);
	}

	public String[] getUploadContentType() {
		return (this.uploadContentType);
	}

	public String[] getUploadFileName() {
		return (this.uploadFileName);
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public MemberService getMemberService() {
		return memberService;
	}

	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}

	public List<String> getRepeatMember() {
		return repeatMember;
	}

	public void setRepeatMember(List<String> repeatMember) {
		this.repeatMember = repeatMember;
	}

	public BaseMemberService getBaseMemberService() {
		return baseMemberService;
	}

	public void setBaseMemberService(BaseMemberService baseMemberService) {
		this.baseMemberService = baseMemberService;
	}

	public EnterpriseIntegralRuleService getEnterpriseIntegralRuleService() {
		return enterpriseIntegralRuleService;
	}

	public void setEnterpriseIntegralRuleService(
			EnterpriseIntegralRuleService enterpriseIntegralRuleService) {
		this.enterpriseIntegralRuleService = enterpriseIntegralRuleService;
	}

}
